//
//  SetIPController.m
//  OneBox
//
//  Created by dev on 16/1/18.
//  Copyright © 2016年 donglian@eastunion.net. All rights reserved.
//

#import "SetIPController.h"
#import "MainController.h"
#import "MBProgressHUD+MJ.h"


@interface SetIPController ()<UITextFieldDelegate>
- (IBAction)submitBtn;
- (IBAction)cancelBtn;

@property (strong, nonatomic)UIScrollView *scrollView;

@end

@implementation SetIPController



- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    _IPText.delegate = self;
    
    self.navigationController.navigationBar.hidden = YES;
    
//    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    _IPText.text = [defaults objectForKey:@"IP"];
    
    
    
}


#pragma mark - 判断是否是IP地址
- (BOOL)isValidateIPDress:(NSString *)IPStr {
    NSString *IPRegex = @"^(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?))$";
    NSPredicate *IPTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", IPRegex];
    return [IPTest evaluateWithObject:IPStr];
}

- (IBAction)submitBtn {
    
    // 把IP存入沙河
    if (_IPText.text.length > 0) {
        
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:_IPText.text forKey:@"IP"];
        
        [defaults synchronize];
        
//        NSLog(@"_IPText------%@", _IPText.text);
        // 1.判断IP地址是否正确
        BOOL isIP = [self isValidateIPDress:_IPText.text];
        // 2.如果正确
        if (isIP) {
            UIStoryboard * mainStoryBoard =[UIStoryboard storyboardWithName:@"Main" bundle:nil];
            MainController *mc = [mainStoryBoard instantiateViewControllerWithIdentifier:@"MainController"];
            
            [self.navigationController pushViewController:mc animated:YES];
        }else{
            [MBProgressHUD showError:@"您输入的IP格式不对"];
            
        }
    }else if (_IPText.text.length == 0){
        [MBProgressHUD showError:@"请输入IP"];
    }
    
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.IPText endEditing:YES];
    return YES;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (IBAction)cancelBtn {
    
    // 1.判断IP地址是否正确
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *textIP = [defaults objectForKey:@"IP"];
    
        if ([_IPText.text isEqualToString:textIP]) {
            
            if ([[self.navigationController.viewControllers objectAtIndex:1] isKindOfClass:[MainController class]]) {
                [self.navigationController popViewControllerAnimated:YES];
        }
    }
}


@end
